package com.twu.biblioteca;

import java.io.IOException;

/**
 * Created by thoughtworker on 1/21/14.
 */
public class BookReturner implements LibraryAction {
    private String ACTION_NAME = "3 - Return a book";
    private Library library;
    private IOManager ioManager;

    public BookReturner(Library library, IOManager ioManager) {
        this.library = library;
        this.ioManager = ioManager;
    }

    @Override
    public void performAction() {
        ioManager.print("Please name of book you wish to return:");
        String title = getInput();
        LibraryBook book = library.findBook(title);
        returnBook(book);
    }

    private String getInput() {
        String title = "";
        try {
            title = ioManager.getUserInput();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return title;
    }

    @Override
    public String toString(){
        return ACTION_NAME;
    }

    public void returnSuccess() {
        ioManager.print("Thank you for returning the book");
    }

    public void returnFailure() {
        ioManager.print("That is not a valid book to return");
    }

    public void returnBook(LibraryBook book) {
        if(book == null){
            returnFailure();
        }
        else if(book.tryReturn()){
            returnSuccess();
        }
        else{
        returnFailure();
        }

    }
}
